﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using UtilZ.Dotnet.Ex.Base;

namespace UtilZ.Dotnet.Ex.Config
{
    /// <summary>
    /// 配置读写类
    /// </summary>
    internal partial class ConfigCore
    {

        #region Write
        /// <summary>
        /// 写配置到XDocument
        /// </summary>
        /// <param name="config">配置对象</param>
        /// <returns>配置XDocument</returns>
        public XDocument WriteConfigToXDocument(object config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            ConfigAttributeTypes configAttributeTypes = new ConfigAttributeTypes();
            XDocument xdoc = new XDocument();
            Type configType = config.GetType();
            ConfigRootAttribute configRootAttribute = ConfigRootAttribute.GetRootConfigRootAttribute(configType, configAttributeTypes);
            XElement rootEle = new XElement(configRootAttribute.GetName(configType));
            this.AddDes(rootEle, configRootAttribute.Des);

            PropertyInfo[] propertyInfoArr = this.GetTypePropertyInfos(configType);
            this.WriteConfigToXml(rootEle, propertyInfoArr, config, configAttributeTypes);
            xdoc.Add(rootEle);
            return xdoc;
        }

        private PropertyInfo[] Sort(PropertyInfo[] ownerObjPropertyInfoArr, ConfigAttributeTypes configAttributeTypes)
        {
            List<PropertyInfoConfigItem> list = null;
            ConfigAttribute attri = null;

            foreach (var propertyInfo in ownerObjPropertyInfoArr)
            {
#if NET4_0
                IEnumerable<Attribute> attributes = TypeEx.GetCustomAttributes(propertyInfo, true);
#else
                IEnumerable<Attribute> attributes = propertyInfo.GetCustomAttributes();
#endif

                attri = null;
                foreach (var att in attributes)
                {
                    if (att is ConfigIgnoreAttribute)
                    {
                        attri = null;
                        break;
                    }
                    else if (att is ConfigAttribute)
                    {
                        attri = (ConfigAttribute)att;
                        break;
                    }
                }

                if (attri == null)
                {
                    continue;
                }

                if (list == null)
                {
                    list = new List<PropertyInfoConfigItem>();
                }

                list.Add(new PropertyInfoConfigItem(attri.Order, propertyInfo));
            }

            if (list == null)
            {
                return ownerObjPropertyInfoArr;
            }
            else
            {
                return list.OrderBy(t =>
                {
                    return t.Order;
                }).Select(p =>
                {
                    return p.PropertyInfo;
                }).ToArray();
            }
        }


        private void WriteConfigToXml(XElement ownerEle, PropertyInfo[] ownerObjPropertyInfoArr, object ownerObj, ConfigAttributeTypes configAttributeTypes)
        {
            if (ownerObj == null)
            {
                return;
            }

            PropertyInfo[] propertyInfos = Sort(ownerObjPropertyInfoArr, configAttributeTypes);
            ConfigAttribute attri = null;
            object propertyValue;
            string name, eleName, comment;
            Type eleType;
            TypeCategorys configDataType;

            foreach (var propertyInfo in propertyInfos)
            {
                try
                {
                    attri = propertyInfo.GetCustomAttribute(configAttributeTypes.IgnoreAttributeType, false) as ConfigIgnoreAttribute;
                    if (attri != null)
                    {
                        //忽略该属性
                        continue;
                    }

                    propertyValue = propertyInfo.GetValue(ownerObj, null);
                    attri = propertyInfo.GetCustomAttribute(configAttributeTypes.ConfigCommentAttributeType, false) as ConfigCommentAttribute;
                    if (attri != null)
                    {
                        //注释
                        if (propertyValue != null)
                        {
                            if (propertyValue is string)
                            {
                                comment = (string)propertyValue;
                            }
                            else
                            {
                                comment = propertyValue.ToString();
                            }

                            ownerEle.Add(new XComment(comment));
                        }

                        continue;
                    }


                    configDataType = this.GetDataType(propertyInfo.PropertyType);

                    attri = propertyInfo.GetCustomAttribute(configAttributeTypes.CustomerAttributeType, false) as ConfigCustomerAttribute;
                    if (attri != null)
                    {
                        //自定义
                        var configItemCustomerAttribute = (ConfigCustomerAttribute)attri;
                        configItemCustomerAttribute.CustomerConfig.Write(propertyInfo, propertyValue, ownerEle, configItemCustomerAttribute);
                        continue;
                    }

                    attri = propertyInfo.GetCustomAttribute(configAttributeTypes.CollectionAttributeType, false) as ConfigCollectionAttribute;
                    if (attri != null)
                    {
                        //集合
                        var collectionAtt = (ConfigCollectionAttribute)attri;
                        name = collectionAtt.GetName(propertyInfo);
                        if (configDataType == TypeCategorys.IDictionary)
                        {
                            eleName = this.GetIDictionaryElementName(collectionAtt.ElementName);
                            this.WriteIDictionary(ownerEle, (IDictionary)propertyValue, propertyInfo.PropertyType, name, eleName, collectionAtt.Des, configAttributeTypes);
                        }
                        else if (configDataType == TypeCategorys.IList)
                        {
                            if (collectionAtt != null && propertyValue == null && !collectionAtt.AllowNullValueElement)
                            {
                                continue;
                            }

                            eleType = this.GetIListElementType(propertyInfo.PropertyType);
                            eleName = collectionAtt.GetElementName(eleType);
                            this.WriteIList(name, eleName, collectionAtt.Des, ownerEle, (IList)propertyValue, propertyInfo.PropertyType, configAttributeTypes);
                        }
                        else
                        {
                            throw new NotImplementedException(configDataType.ToString());
                        }
                        continue;
                    }

                    attri = propertyInfo.GetCustomAttribute(configAttributeTypes.ObjectAttributeType, false) as ConfigObjectAttribute;
                    if (attri != null)
                    {
                        //复合对象
                        this.WriteObject(ownerEle, configAttributeTypes, (ConfigObjectAttribute)attri, propertyValue, propertyInfo);
                        continue;
                    }

                    attri = propertyInfo.GetCustomAttribute(configAttributeTypes.ItemAttributeType, false) as ConfigAttribute;
                    if (attri != null)
                    {
                        //基元项
                        this.WriteItem(ownerEle, (ConfigItemAttribute)attri, propertyValue, propertyInfo);
                        continue;
                    }


                    //未标记项====================================================================================================


                    switch (configDataType)
                    {
                        case TypeCategorys.IDictionary:
                            name = this.GetIDictionaryName(null, propertyInfo);
                            eleName = this.GetIDictionaryElementName(null);
                            this.WriteIDictionary(ownerEle, (IDictionary)propertyValue, propertyInfo.PropertyType, name, eleName, null, configAttributeTypes);
                            break;
                        case TypeCategorys.IList:
                            name = this.GetConfigItemName(propertyInfo);
                            eleType = this.GetIListElementType(propertyInfo.PropertyType);
                            eleName = this.GetIListElementName(eleType);
                            this.WriteIList(name, eleName, null, ownerEle, (IList)propertyValue, propertyInfo.PropertyType, configAttributeTypes);
                            break;
                        case TypeCategorys.Object:
                            this.WriteObject(ownerEle, configAttributeTypes, propertyValue, propertyInfo);
                            break;
                        case TypeCategorys.Basic:
                            this.WriteItem(ownerEle, propertyValue, propertyInfo);
                            break;
                        default:
                            throw new NotImplementedException(configDataType.ToString());
                    }
                }
                catch (XmlException ex)
                {
                    string errMsg;
                    if (attri != null)
                    {
                        errMsg = $"类型{ownerObj.GetType().FullName}中的属性{propertyInfo.Name}对应的配置项名称\"{attri.Name}\"错误，不能包含空格等特殊字符";
                    }
                    else
                    {
                        errMsg = $"类型{ownerObj.GetType().FullName}中的属性{propertyInfo.Name}对应的配置项名称错误，不能包含空格等特殊字符";
                    }
                    throw new ArgumentException(errMsg, ex);
                }
            }
        }

        private void WriteIList(string name, string eleName, string des, XElement ownerEle, IList list, Type listType, ConfigAttributeTypes configAttributeTypes)
        {
            XElement collectionEle = new XElement(name);
            this.AddDes(collectionEle, des);
            ownerEle.Add(collectionEle);

            var eleType = this.GetIListElementType(listType);
            this.WriteIList(eleName, collectionEle, list, eleType, configAttributeTypes);
        }


        private void WriteIList(string name, XElement collectionEle, IList list, Type eleType, ConfigAttributeTypes configAttributeTypes)
        {
            if (list == null || list.Count == 0)
            {
                return;
            }

            string eleName = this.GetIListElementName(eleType), eleName2 = null;
            TypeCategorys configDataType = this.GetDataType(eleType);
            switch (configDataType)
            {
                case TypeCategorys.IDictionary:
                    eleName2 = this.GetIDictionaryElementName(null);
                    foreach (var item in list)
                    {
                        this.WriteIDictionary(collectionEle, (IDictionary)item, eleType, eleName, eleName2, null, configAttributeTypes);
                    }
                    break;
                case TypeCategorys.IList:
                    var itemType2 = this.GetIListElementType(eleType);
                    eleName = this.GetIListElementName(itemType2);
                    foreach (var item in list)
                    {
                        XElement itemEle = new XElement(name);
                        collectionEle.Add(itemEle);
                        this.WriteIList(eleName, itemEle, (IList)item, itemType2, configAttributeTypes);
                    }
                    break;
                case TypeCategorys.Object:
                    PropertyInfo[] objPropertyInfoArr = this.GetTypePropertyInfos(eleType);
                    foreach (var item in list)
                    {
                        if (item == null)
                        {
                            continue;
                        }

                        XElement childEle = new XElement(name);
                        this.WriteConfigToXml(childEle, objPropertyInfoArr, item, configAttributeTypes);
                        collectionEle.Add(childEle);
                    }
                    break;
                case TypeCategorys.Basic:
                    foreach (var item in list)
                    {
                        this.WriteItem(collectionEle, name, item, null);
                    }
                    break;
                default:
                    throw new NotImplementedException(configDataType.ToString());
            }
        }


        private void WriteIDictionary(XElement ownerEle, IDictionary dic, Type dicType, string name, string eleName, string des, ConfigAttributeTypes configAttributeTypes)
        {
            if (dic == null || dic.Count == 0)
            {
                return;
            }

            XElement dicEle = new XElement(name);
            this.AddDes(dicEle, des);
            ownerEle.Add(dicEle);

            object value;
            Type[] argsTypeArr = dicType.GetGenericArguments();
            TypeCategorys keyDataType = this.GetDataType(argsTypeArr[0]);
            TypeCategorys valueDataType = this.GetDataType(argsTypeArr[1]);
            PropertyInfo[] objPropertyInfoArr = null;
            string name2 = null, eleName2 = null, eleName3 = null;
            Type eleType = null;

            foreach (var key in dic.Keys)
            {
                XElement eleEle = new XElement(eleName);
                dicEle.Add(eleEle);

                //key
                XElement keyEle = new XElement(_KEY);
                switch (keyDataType)
                {
                    case TypeCategorys.Basic:
                        keyEle.Add(new XAttribute(_VALUE, key.ToString()));
                        break;
                    case TypeCategorys.IDictionary:
                    case TypeCategorys.IList:
                    case TypeCategorys.Object:
                    default:
                        throw new NotSupportedException($"字典集合的key只能为基础类型数据,类型{keyDataType.ToString()}无效");
                }
                eleEle.Add(keyEle);


                value = dic[key];
                XElement valueEle = new XElement(_VALUE);
                switch (valueDataType)
                {
                    case TypeCategorys.Basic:
                        if (value != null)
                        {
                            valueEle.Add(new XAttribute(_VALUE, value.ToString()));
                        }
                        break;
                    case TypeCategorys.IDictionary:
                        if (name2 == null)
                        {
                            name2 = this.GetIListElementName(argsTypeArr[1]);
                        }

                        if (eleName2 == null)
                        {
                            eleName2 = this.GetIDictionaryElementName(null);
                        }

                        this.WriteIDictionary(valueEle, (IDictionary)value, argsTypeArr[1], name2, eleName2, null, configAttributeTypes);
                        break;
                    case TypeCategorys.IList:
                        if (eleType == null)
                        {
                            eleType = this.GetIListElementType(argsTypeArr[1]);
                        }

                        if (eleName2 == null)
                        {
                            eleName2 = this.GetIListElementName(argsTypeArr[1]);
                        }

                        if (eleName3 == null)
                        {
                            eleName3 = this.GetIListElementName(eleType);
                        }
                        XElement listChildEle = new XElement(eleName2);
                        this.WriteIList(eleName3, listChildEle, (IList)value, eleType, configAttributeTypes);
                        valueEle.Add(listChildEle);
                        break;
                    case TypeCategorys.Object:
                        if (objPropertyInfoArr == null)
                        {
                            objPropertyInfoArr = this.GetTypePropertyInfos(argsTypeArr[1]);
                        }

                        if (eleName2 == null)
                        {
                            eleName2 = this.GetIListElementName(argsTypeArr[1]);
                        }

                        XElement childEle = new XElement(eleName2);
                        this.WriteConfigToXml(childEle, objPropertyInfoArr, value, configAttributeTypes);
                        valueEle.Add(childEle);
                        break;
                    default:
                        throw new NotSupportedException(valueDataType.ToString());
                }

                eleEle.Add(valueEle);
            }
        }






        private void WriteObject(XElement ownerEle, ConfigAttributeTypes configAttributeTypes, object propertyValue, PropertyInfo propertyInfo)
        {
            string complexEleName = this.GetConfigItemName(propertyInfo);
            XElement complexEle = new XElement(complexEleName);
            ownerEle.Add(complexEle);

            if (propertyValue != null)
            {
                PropertyInfo[] complexPropertyInfoArr = this.GetTypePropertyInfos(propertyInfo.PropertyType);
                this.WriteConfigToXml(complexEle, complexPropertyInfoArr, propertyValue, configAttributeTypes);
            }
        }

        private void WriteObject(XElement ownerEle, ConfigAttributeTypes configAttributeTypes, ConfigObjectAttribute attri, object propertyValue, PropertyInfo propertyInfo)
        {
            if (!attri.AllowNullValueElement && propertyValue == null)
            {
                return;
            }

            XElement complexEle = new XElement(attri.GetName(propertyInfo));
            this.AddDes(complexEle, attri.Des);
            ownerEle.Add(complexEle);

            if (propertyValue != null)
            {
                PropertyInfo[] complexPropertyInfoArr = this.GetTypePropertyInfos(propertyInfo.PropertyType);
                this.WriteConfigToXml(complexEle, complexPropertyInfoArr, propertyValue, configAttributeTypes);
            }
        }


        private void WriteItem(XElement ownerEle, object propertyInfoValue, PropertyInfo propertyInfo)
        {
            string value = this.GetStringValue(null, propertyInfoValue, propertyInfo);
            string childEleName = this.GetConfigItemName(propertyInfo);
            this.WriteItem(ownerEle, childEleName, value, null);
        }


        private void WriteItem(XElement ownerEle, ConfigItemAttribute attri, object propertyValue, PropertyInfo propertyInfo)
        {
            if (!attri.AllowNullValueElement && propertyValue == null)
            {
                return;
            }

            string value = this.GetStringValue(attri.GetConverter(propertyInfo), propertyValue, propertyInfo);
            string childEleName = attri.GetName(propertyInfo);
            this.WriteItem(ownerEle, childEleName, value, attri.Des);
        }

        private void WriteItem(XElement ownerEle, string eleName, object value, string des)
        {
            if (string.IsNullOrWhiteSpace(eleName))
            {
                throw new ArgumentNullException(nameof(eleName));
            }

            XElement ele = new XElement(eleName);
            if (value != null)
            {
                ele.Add(new XAttribute(_VALUE, value));
            }

            this.AddDes(ele, des);
            ownerEle.Add(ele);
        }

        private string GetStringValue(IConfigValueConverter converter, object propertyInfoValue, PropertyInfo propertyInfo)
        {
            string strValue;
            if (converter != null)
            {
                strValue = converter.ConvertTo(propertyInfo, propertyInfoValue);
            }
            else
            {
                if (propertyInfoValue == null)
                {
                    strValue = string.Empty;
                }
                else
                {
                    if (propertyInfoValue is string)
                    {
                        strValue = (string)propertyInfoValue;
                    }
                    else
                    {
                        strValue = propertyInfoValue.ToString();
                    }
                }
            }

            return strValue;
        }

        private void AddDes(XElement ele, string des)
        {
            if (!string.IsNullOrWhiteSpace(des))
            {
                ele.Add(new XAttribute(nameof(ConfigItemAttribute.Des), des));
            }
        }
        #endregion

    }
}
